import Vue from 'vue'
import ShowModule from '../components/com-show-module.vue'
import {Tools} from './tools'

const ModuleConstructor = Vue.extend(ShowModule)

const hideModule = () => {
    let element = document.getElementById('showModule')
    if(element) document.body.removeChild(element);
}
const showModule = (options) => {
    let instance = new ModuleConstructor()
    instance.vm = instance.$mount()
    try{
        if (Object.prototype.toString.call(options) !== '[object Object]') {
            throw new Error('options must be Object')
        }
        if (!options.confirmColor || !Tools.check.isColor16Hex(options.confirmColor)) {
            throw new Error('confirmColor must be hexadecimal format')
        }
    } catch(err){
        console.error(err)
        return
    }
    if (options.cancleText === false) instance.vm.cancleText = '';
    else instance.vm.cancleText = options.cancleText;
    instance.vm.title = options.title || ''
    instance.vm.content = options.content || ''
    instance.vm.confirmColor = options.confirmColor || '#000000'
    instance.vm.confirmText = options.confirmText || '确定'
    const {
        cancleFunc,
        confirmFunc
    } = options
    instance.vm.$on('cancle', () => {
        if (Object.prototype.toString.call(cancleFunc) === '[object Function]') {
            cancleFunc()
        }
        instance.vm.visible = false
    })
    instance.vm.$on('confirm', () => {
        if (Object.prototype.toString.call(confirmFunc) === '[object Function]') {
            confirmFunc()
        }
        instance.vm.visible = false
    })
    instance.vm.$on('close', () => {
        document.body.removeChild(instance.vm.$el)
        instance.vm.$destroy()
    })
    instance.vm.visible = true
    document.body.appendChild(instance.vm.$el)
}

export default {
    showModule,
    hideModule
}